import Foundation

// 配置管理类
class ConfigManager {
    private let configPath: String
    
    struct Config {
        var ytDlpPath: String
        var outputDirectory: String
        var proxyUrl: String?
        var maxConcurrentDownloads: Int
        var cleanupDays: Int
        var enableLogging: Bool
        var tempDirectory: String
        
        static func defaultConfig() -> Config {
            let homeDir = NSHomeDirectory()
            return Config(
                ytDlpPath: "/opt/homebrew/bin/yt-dlp",
                outputDirectory: "\(homeDir)/Downloads/VideoDownloader",
                proxyUrl: nil,
                maxConcurrentDownloads: 2,
                cleanupDays: 30,
                enableLogging: true,
                tempDirectory: "\(homeDir)/.vdh/temp"
            )
        }
    }
    
    private var config: Config
    
    init() {
        let vdhDir = NSHomeDirectory() + "/.vdh"
        self.configPath = vdhDir + "/config.yaml"
        
        // 初始化为默认配置
        self.config = Config.defaultConfig()
        
        // 确保.vdh目录存在
        try? FileManager.default.createDirectory(atPath: vdhDir, withIntermediateDirectories: true)
        
        // 加载或创建配置
        self.config = loadConfig()
        
        // 确保输出目录和临时目录存在
        try? FileManager.default.createDirectory(atPath: config.outputDirectory, withIntermediateDirectories: true)
        try? FileManager.default.createDirectory(atPath: config.tempDirectory, withIntermediateDirectories: true)
    }
    
    private func loadConfig() -> Config {
        guard FileManager.default.fileExists(atPath: configPath) else {
            // 如果配置文件不存在，创建默认配置
            let defaultConfig = Config.defaultConfig()
            saveConfig(defaultConfig)
            print("✅ Created default config at: \(configPath)")
            return defaultConfig
        }
        
        do {
            let yamlContent = try String(contentsOfFile: configPath, encoding: .utf8)
            return parseYAML(yamlContent) ?? Config.defaultConfig()
        } catch {
            print("❌ Failed to read config file: \(error)")
            return Config.defaultConfig()
        }
    }
    
    private func parseYAML(_ content: String) -> Config? {
        var config = Config.defaultConfig()
        
        let lines = content.components(separatedBy: .newlines)
        for line in lines {
            let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
            if trimmed.isEmpty || trimmed.hasPrefix("#") {
                continue
            }
            
            let components = trimmed.components(separatedBy: ": ")
            guard components.count >= 2 else { continue }
            
            let key = components[0].trimmingCharacters(in: .whitespacesAndNewlines)
            let value = components[1...].joined(separator: ": ").trimmingCharacters(in: .whitespacesAndNewlines)
            
            // 移除引号
            let cleanValue = value.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
            
            switch key {
            case "yt_dlp_path":
                config.ytDlpPath = cleanValue
            case "output_directory":
                config.outputDirectory = expandPath(cleanValue)
            case "proxy_url":
                config.proxyUrl = cleanValue.isEmpty ? nil : cleanValue
            case "max_concurrent_downloads":
                config.maxConcurrentDownloads = Int(cleanValue) ?? 2
            case "cleanup_days":
                config.cleanupDays = Int(cleanValue) ?? 30
            case "enable_logging":
                config.enableLogging = Bool(cleanValue) ?? true
            case "temp_directory":
                config.tempDirectory = expandPath(cleanValue)
            default:
                continue
            }
        }
        
        return config
    }
    
    private func expandPath(_ path: String) -> String {
        if path.hasPrefix("~") {
            return path.replacingOccurrences(of: "~", with: NSHomeDirectory())
        }
        return path
    }
    
    private func saveConfig(_ config: Config) {
        let yamlContent = generateYAML(config)
        
        do {
            try yamlContent.write(toFile: configPath, atomically: true, encoding: .utf8)
            print("✅ Config saved to: \(configPath)")
        } catch {
            print("❌ Failed to save config: \(error)")
        }
    }
    
    private func generateYAML(_ config: Config) -> String {
        var yaml = """
        # VDH (Video Downloader Helper) Configuration File
        # This file is automatically generated and can be manually edited
        
        # Path to yt-dlp executable
        yt_dlp_path: "\(config.ytDlpPath)"
        
        # Directory where downloaded videos will be saved
        output_directory: "\(config.outputDirectory)"
        
        # Proxy URL (optional) - format: http://proxy:port or socks5://proxy:port
        """
        
        if let proxyUrl = config.proxyUrl {
            yaml += "\nproxy_url: \"\(proxyUrl)\""
        } else {
            yaml += "\n# proxy_url: \"http://proxy:8080\""
        }
        
        yaml += """
        
        
        # Maximum number of concurrent downloads
        max_concurrent_downloads: \(config.maxConcurrentDownloads)
        
        # Number of days to keep completed/failed tasks before cleanup
        cleanup_days: \(config.cleanupDays)
        
        # Enable detailed logging
        enable_logging: \(config.enableLogging)
        
        # Temporary directory for downloads in progress
        temp_directory: "\(config.tempDirectory)"
        """
        
        return yaml
    }
    
    func getConfig() -> Config {
        return config
    }
    
    func updateConfig(_ newConfig: Config) {
        self.config = newConfig
        saveConfig(newConfig)
        
        // 确保目录存在
        try? FileManager.default.createDirectory(atPath: config.outputDirectory, withIntermediateDirectories: true)
        try? FileManager.default.createDirectory(atPath: config.tempDirectory, withIntermediateDirectories: true)
    }
    
    func reloadConfig() {
        self.config = loadConfig()
    }
    
    func printConfig() {
        print("📋 VDH Configuration:")
        print("  yt-dlp path: \(config.ytDlpPath)")
        print("  Output directory: \(config.outputDirectory)")
        print("  Proxy: \(config.proxyUrl ?? "None")")
        print("  Max concurrent: \(config.maxConcurrentDownloads)")
        print("  Cleanup days: \(config.cleanupDays)")
        print("  Logging: \(config.enableLogging)")
        print("  Temp directory: \(config.tempDirectory)")
        print("  Config file: \(configPath)")
    }
}